
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using Apps.Models;
using Apps.Common;
using Microsoft.Practices.Unity;
using System.Transactions;
using Apps.BLL.Core;
using Apps.Locale;
using LinqToExcel;
using System.IO;
using System.Text;
using System.Linq.Expressions;
using Apps.IDAL.PL;
using Apps.Models.PL;
using Apps.IBLL.PL;
namespace Apps.BLL.PL
{
    public partial class PL_RC_PLANSBLL : Virtual_PL_RC_PLANSBLL, IPL_RC_PLANSBLL
    {


    }
    public class Virtual_PL_RC_PLANSBLL
    {
        [Dependency]
        public IPL_RC_PLANSRepository m_Rep { get; set; }

        public virtual List<PL_RC_PLANSModel> GetList(ref GridPager pager, string queryStr)
        {

            IQueryable<PL_RC_PLANS> queryData = null;
            if (!string.IsNullOrWhiteSpace(queryStr))
            {
                queryData = m_Rep.GetList(
                                a => a.PLAN_ID.Contains(queryStr)

                                || a.PLAN_USER_ID.Contains(queryStr)



                                );
            }
            else
            {
                queryData = m_Rep.GetList();
            }
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

        public virtual List<PL_RC_PLANSModel> GetPagerList(ref GridPager pager, Expression<Func<PL_RC_PLANS, bool>> whereLambda)
        {

            IQueryable<PL_RC_PLANS> queryData = m_Rep.GetList(whereLambda);

            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

        public virtual List<PL_RC_PLANSModel> GetList(Expression<Func<PL_RC_PLANS, bool>> whereLambda)
        {

            IQueryable<PL_RC_PLANS> queryData = m_Rep.GetList(whereLambda);

            return CreateModelList(ref queryData);
        }

        public virtual List<PL_RC_PLANSModel> GetListByParentId(ref GridPager pager, string queryStr, object parentId)
        {
            return new List<PL_RC_PLANSModel>();
        }

        public virtual List<PL_RC_PLANSModel> CreateModelList(ref IQueryable<PL_RC_PLANS> queryData)
        {

            List<PL_RC_PLANSModel> modelList = (from r in queryData
                                                select new PL_RC_PLANSModel
                                                {
                                                    PLAN_ID = r.PLAN_ID,
                                                    PLAN_DATE = r.PLAN_DATE,
                                                    PLAN_USER_ID = r.PLAN_USER_ID,
                                                    CREATE_TIME = r.CREATE_TIME,
                                                    PUBLISHED = r.PUBLISHED,
                                                    PUBLISH_TIME = r.PUBLISH_TIME,
                                                    SumAmount = r.PL_RC_DETAILS.Sum(p => p.AMOUNT),
                                                    SumQnet = (((decimal?)r.PL_RC_DETAILS.Sum(p => p.QNET)) ?? 0) == 0 ? 0 : r.PL_RC_DETAILS.Sum(p => p.QNET * p.AMOUNT) / r.PL_RC_DETAILS.Sum(p => p.AMOUNT),
                                                    SumSt = (((decimal?)r.PL_RC_DETAILS.Sum(p => p.QNET)) ?? 0) == 0 ? 0 : r.PL_RC_DETAILS.Sum(p => p.ST * p.AMOUNT) / r.PL_RC_DETAILS.Sum(p => p.AMOUNT)

                                                }).ToList();
            List<PL_RC_PLANSModel> newModelist ;
            using (DBContainer db = new DBContainer())
            {
                  newModelist = (from r in modelList
                                   join u in db.SysUser on r.PLAN_USER_ID equals u.Id
                                   select new PL_RC_PLANSModel
                                   {
                                       PLAN_ID = r.PLAN_ID,
                                       PLAN_DATE = r.PLAN_DATE,
                                       PLAN_USER_ID = u.TrueName,
                                       CREATE_TIME = r.CREATE_TIME,
                                       PUBLISHED = r.PUBLISHED,
                                       PUBLISH_TIME = r.PUBLISH_TIME,
                                       SumAmount = r.SumAmount,
                                       SumQnet = r.SumQnet,
                                       SumSt = r.SumSt

                                   }).ToList();

            }

            return newModelist;
        }

        public virtual bool Create(ref ValidationErrors errors, PL_RC_PLANSModel model)
        {
            try
            {
                PL_RC_PLANS entity = m_Rep.GetById(model.PLAN_ID);
                if (entity != null)
                {
                    errors.Add(Resource.PrimaryRepeat);
                    return false;
                }
                entity = new PL_RC_PLANS();
                entity.PLAN_ID = model.PLAN_ID;
                entity.PLAN_DATE = model.PLAN_DATE;
                entity.PLAN_USER_ID = model.PLAN_USER_ID;
                entity.CREATE_TIME = model.CREATE_TIME;
                entity.PUBLISHED = model.PUBLISHED;
                entity.PUBLISH_TIME = model.PUBLISH_TIME;


                if (m_Rep.Create(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.InsertFail);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }


        public virtual bool Deletes(ref ValidationErrors errors, Expression<Func<PL_RC_PLANS, bool>> whereLambda)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {

                    foreach (var entity in db.PL_RC_PLANS.Where(whereLambda))
                    {
                        db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                    }

                    if (db.SaveChanges() > 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }

                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object id)
        {
            try
            {
                if (m_Rep.Delete(id) == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object[] deleteCollection)
        {
            try
            {
                if (deleteCollection != null)
                {
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        if (m_Rep.Delete(deleteCollection) == deleteCollection.Length)
                        {
                            transactionScope.Complete();
                            return true;
                        }
                        else
                        {
                            Transaction.Current.Rollback();
                            return false;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }




        public virtual bool Edit(ref ValidationErrors errors, PL_RC_PLANSModel model)
        {
            try
            {
                PL_RC_PLANS entity = m_Rep.GetById(model.PLAN_ID);
                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return false;
                }
                entity.PLAN_ID = model.PLAN_ID;
                entity.PLAN_DATE = model.PLAN_DATE;
                entity.PLAN_USER_ID = model.PLAN_USER_ID;
                entity.CREATE_TIME = model.CREATE_TIME;
                entity.PUBLISHED = model.PUBLISHED;
                entity.PUBLISH_TIME = model.PUBLISH_TIME;



                if (m_Rep.Edit(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.NoDataChange);
                    return false;
                }

            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }



        public virtual PL_RC_PLANSModel GetById(object id)
        {
            if (IsExists(id))
            {
                PL_RC_PLANS entity = m_Rep.GetById(id);
                PL_RC_PLANSModel model = new PL_RC_PLANSModel();
                model.PLAN_ID = entity.PLAN_ID;
                model.PLAN_DATE = entity.PLAN_DATE;
                model.PLAN_USER_ID = entity.PLAN_USER_ID;
                model.CREATE_TIME = entity.CREATE_TIME;
                model.PUBLISHED = entity.PUBLISHED;
                model.PUBLISH_TIME = entity.PUBLISH_TIME;

                return model;
            }
            else
            {
                return null;
            }
        }

        public virtual PL_RC_PLANSModel GetItem(Expression<Func<PL_RC_PLANS, bool>> whereLambda)
        {

            PL_RC_PLANS entity = m_Rep.GetItem(whereLambda);
            if (entity == null) return null;

            PL_RC_PLANSModel model = new PL_RC_PLANSModel();
            model.PLAN_ID = entity.PLAN_ID;
            model.PLAN_DATE = entity.PLAN_DATE;
            model.PLAN_USER_ID = entity.PLAN_USER_ID;
            model.CREATE_TIME = entity.CREATE_TIME;
            model.PUBLISHED = entity.PUBLISHED;
            model.PUBLISH_TIME = entity.PUBLISH_TIME;

            return model;
        }


        /// <summary>
        /// 校验Excel数据,这个方法一般用于重写校验逻辑
        /// </summary>
        public virtual bool CheckImportData(string fileName, List<PL_RC_PLANSModel> list, ref ValidationErrors errors)
        {

            var targetFile = new FileInfo(fileName);

            if (!targetFile.Exists)
            {

                errors.Add("导入的数据文件不存在");
                return false;
            }

            var excelFile = new ExcelQueryFactory(fileName);

            //对应列头
            excelFile.AddMapping<PL_RC_PLANSModel>(x => x.PLAN_ID, "PLAN_ID");
            excelFile.AddMapping<PL_RC_PLANSModel>(x => x.PLAN_DATE, "PLAN_DATE");
            excelFile.AddMapping<PL_RC_PLANSModel>(x => x.PLAN_USER_ID, "PLAN_USER_ID");
            excelFile.AddMapping<PL_RC_PLANSModel>(x => x.CREATE_TIME, "CREATE_TIME");
            excelFile.AddMapping<PL_RC_PLANSModel>(x => x.PUBLISHED, "PUBLISHED");
            excelFile.AddMapping<PL_RC_PLANSModel>(x => x.PUBLISH_TIME, "PUBLISH_TIME");

            //SheetName
            var excelContent = excelFile.Worksheet<PL_RC_PLANSModel>(0);
            int rowIndex = 1;
            //检查数据正确性
            foreach (var row in excelContent)
            {
                var errorMessage = new StringBuilder();
                var entity = new PL_RC_PLANSModel();
                entity.PLAN_ID = row.PLAN_ID;
                entity.PLAN_DATE = row.PLAN_DATE;
                entity.PLAN_USER_ID = row.PLAN_USER_ID;
                entity.CREATE_TIME = row.CREATE_TIME;
                entity.PUBLISHED = row.PUBLISHED;
                entity.PUBLISH_TIME = row.PUBLISH_TIME;

                //=============================================================================
                if (errorMessage.Length > 0)
                {
                    errors.Add(string.Format(
                        "第 {0} 列发现错误：{1}{2}",
                        rowIndex,
                        errorMessage,
                        "<br/>"));
                }
                list.Add(entity);
                rowIndex += 1;
            }
            if (errors.Count > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        public virtual void SaveImportData(IEnumerable<PL_RC_PLANSModel> list)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    foreach (var model in list)
                    {
                        PL_RC_PLANS entity = new PL_RC_PLANS();
                        entity.PLAN_ID = model.PLAN_ID;
                        entity.PLAN_DATE = model.PLAN_DATE;
                        entity.PLAN_USER_ID = model.PLAN_USER_ID;
                        entity.CREATE_TIME = model.CREATE_TIME;
                        entity.PUBLISHED = model.PUBLISHED;
                        entity.PUBLISH_TIME = model.PUBLISH_TIME;

                        db.PL_RC_PLANS.Add(entity);
                    }
                    db.SaveChanges();
                }
            }
            catch
            {
                throw;
            }
        }


        public virtual bool IsExists(object id)
        {
            return m_Rep.IsExist(id);
        }
        public void Dispose()
        {

        }

    }
}
